package cc.linker.steplink.crm.controller.robot;

import cc.linker.steplink.crm.commons.constant.ContentConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.domain.LabelPo;
import cc.linker.steplink.crm.merchanth5.service.acs.DynamicService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseCode;
import cc.linker.steplink.crm.service.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author snake
 * @date 2019/8/26
 * 智能客户专员机器人
 **/
@Slf4j
@RestController
@RequestMapping("/clientrobot")
public class ClientRobotController {

    @Autowired
    private ISysConfig sysConfigService;
    @Autowired
    private IClientRobotService iClientRobotService;
    @Autowired
    private ILabelService labelService;
    @Autowired
    private ILabelNewService labelNewService;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private CustomerService customerService;

    @Value("${system.scrm.sync.contentUrl}")
    private String synccontentUrl;

    @Autowired
    private HttpService httpService;

    @Value("${system.scrm.defimg}")
    private String defimg;
    @Autowired
    private UserInfoUtil userInfoUtil;

    /**
     * 获取客户专员机器人配置
     *
     * @param session
     * @return
     * @throws GlobalException
     */
    @GetMapping("/getconf")
    public Map GetConf(HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Map<String, Object> resMap = new HashMap<>();
        String clientRobotLimit = sysConfigService.getSysConfByName(orgId, "clientRobotLimit");
        if (null == clientRobotLimit) {
            Map<String, String> tmpParam = new HashMap<>();
            tmpParam.put("orgId", orgId);
            tmpParam.put("value", "1");
            tmpParam.put("desc", "智能客户专员机器人群发推送上限");
            tmpParam.put("name", "clientRobotLimit");
            sysConfigService.addSysConf(tmpParam);
            resMap.put("clientRobotLimit", "1");
        } else {
            resMap.put("clientRobotLimit", clientRobotLimit);
        }

        String clientRobotStartTime = sysConfigService.getSysConfByName(orgId, "clientRobotStartTime");
        if (null == clientRobotStartTime) {
            Map<String, String> tmpParam = new HashMap<>();
            tmpParam.put("orgId", orgId);
            tmpParam.put("value", "08:00:00");
            tmpParam.put("desc", "智能客户专员机器人营销时间");
            tmpParam.put("name", "clientRobotStartTime");
            sysConfigService.addSysConf(tmpParam);
            resMap.put("clientRobotStartTime", "08:00:00");
        } else {
            resMap.put("clientRobotStartTime", clientRobotStartTime);
        }
        return resMap;
    }

    /**
     * 设置客户专员机器人配置
     *
     * @param session
     * @param map
     * @return
     * @throws GlobalException
     */
    @PostMapping("/setconf")
    public Map setConf(HttpServletRequest request, @RequestBody Map<String, String> map) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Map<String, String> resData = new HashMap<>();
        Map<String, String> tmpParam = new HashMap<>();
        tmpParam.put("orgId", orgId);
        String clientRobotLimit = sysConfigService.getSysConfByName(orgId, "clientRobotLimit");
        resData.put("clientRobotLimit", clientRobotLimit);
        if (null != map.get("clientRobotLimit")) {
            if (null != clientRobotLimit) {
                tmpParam.put("value", map.get("clientRobotLimit"));
                tmpParam.put("name", "clientRobotLimit");
                Boolean setLimit = sysConfigService.updateSysConf(tmpParam);
                if (!setLimit) {
                    throw GlobalException.build("操作失败");
                }
            } else {
                throw GlobalException.build("非法操作");
            }
            resData.put("clientRobotLimit", map.get("clientRobotLimit"));
        }

        String clientRobotStartTime = sysConfigService.getSysConfByName(orgId, "clientRobotStartTime");
        resData.put("clientRobotStartTime", clientRobotStartTime);
        if (null != map.get("clientRobotStartTime")) {
            if (null != clientRobotLimit) {
                tmpParam.put("value", map.get("clientRobotStartTime"));
                tmpParam.put("name", "clientRobotStartTime");
                Boolean setTime = sysConfigService.updateSysConf(tmpParam);
                if (!setTime) {
                    throw GlobalException.build("操作失败");
                }
            } else {
                throw GlobalException.build("非法操作");
            }
            resData.put("clientRobotStartTime", map.get("clientRobotStartTime"));
        }
        return resData;
    }

    /**
     * 获取客户专员机器人开关
     *
     * @param session
     * @return
     * @throws GlobalException
     */
    @GetMapping("/getswitch")
    public Map getSwitch(HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Map<String, Object> resMap = new HashMap<>();
        String clientRobotSwitch = sysConfigService.getSysConfByName(orgId, "clientRobotSwitch");
        if (null == clientRobotSwitch) {
            Map<String, String> tmpParam = new HashMap<>();
            tmpParam.put("orgId", orgId);
            tmpParam.put("value", "0");
            tmpParam.put("desc", "智能客户专员机器人开关(0:关闭，1:打开)");
            tmpParam.put("name", "clientRobotSwitch");
            sysConfigService.addSysConf(tmpParam);
            resMap.put("clientRobotSwitch", "0");
        } else {
            resMap.put("clientRobotSwitch", clientRobotSwitch);
        }

        Map<String, Object> orgFunction = customerService.getOrgFunctionOrgId(orgId);
        Integer robotNum = 0;
        if (orgFunction == null || StringUtils.isEmpty(orgFunction.get("cusNum"))) {
            robotNum = 0;
        } else if (!StringUtils.isEmpty(orgFunction.get("cusExpireDate"))) {
            // 判断时间是否到期
            Long expireTime = dateToStamp(orgFunction.get("cusExpireDate").toString() + " 00:00:00");
            Long nowTime = System.currentTimeMillis();
            if (nowTime > expireTime) {
                robotNum = 0;
            } else {
                robotNum = Integer.parseInt(orgFunction.get("cusNum").toString());
            }
        }
        // 获取当前机构机器人数量
        resMap.put("robotNum", robotNum);
        return resMap;
    }

    /**
     * 设置客户专员机器人开关
     *
     * @param session
     * @return
     * @throws GlobalException
     */
    @PostMapping("/changeswitch")
    public Map changeSwitch(HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Map<String, String> resData = new HashMap<>();
        Boolean setLimit = false;
        String clientRobotSwitch = sysConfigService.getSysConfByName(orgId, "clientRobotSwitch");
        if (null == clientRobotSwitch) {
            throw GlobalException.build("非法操作");
        } else {
            Map<String, String> tmpParam = new HashMap<>();
            tmpParam.put("orgId", orgId);
            tmpParam.put("name", "clientRobotSwitch");
            if ("0".equals(clientRobotSwitch)) {
                tmpParam.put("value", "1");
                resData.put("clientRobotSwitch", "1");
                tmpParam.put("dynamicContent", "客户专员机器人开启");
                tmpParam.put("dynamicType", "3");
                dynamicService.recording(request, 9,"开启客户专员机器人");
            } else {
                tmpParam.put("value", "0");
                resData.put("clientRobotSwitch", "0");
                tmpParam.put("dynamicContent", "客户专员机器人关闭");
                tmpParam.put("dynamicType", "4");
                dynamicService.recording(request, 10,"关闭客户专员机器人");
            }
            setLimit = sysConfigService.updateSysConf(tmpParam);
            tmpParam.put("robotType", "client");
            sysConfigService.saveRobotDynamic(tmpParam);
        }
        if (setLimit) {
            return resData;
        }
        throw GlobalException.build("操作失败");
    }

    /**
     * 营销文库列表
     *
     * @param session
     * @param pageIndex
     * @param pageSize
     * @return
     * @throws Exception
     */
    @GetMapping("/articlelist")
    public Object articleList(HttpServletRequest request,
                              @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                              @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                              @RequestParam(value = "labelId", defaultValue = "", required = false) String labelId,
                              @RequestParam(value = "articleType", defaultValue = "", required = false) String articleType,
                              @RequestParam(value = "articleTitle", defaultValue = "", required = false) String articleTitle
    ) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        PageHelper.startPage(pageIndex, pageSize);
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);

        if (!StringUtils.isEmpty(labelId)) {
            String[] paramsplit = labelId.split(",");
            List<String> paramlabelId = new ArrayList<>(Arrays.asList(paramsplit));
            param.put("labelIds", paramlabelId);
        }
        if (!articleType.isEmpty()) {
            param.put("articleType", articleType);
        }
        if (!articleTitle.isEmpty()) {
            param.put("articleTitle", articleTitle);
        }
        return new PageInfo<>(iClientRobotService.articlelist(param));
    }

    /**
     * 添加营销文章
     *
     * @param session
     * @param map
     * @throws Exception
     */
    @PostMapping("/addrobotarticle")
    public void addRobotArticle(HttpServletRequest request, @RequestBody List<Map<String, String>> map) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        for (Map<String, String> x : map) {
            StringBuilder labelId = new StringBuilder();
            String label = x.get("labelName") == null ? "" : x.get("labelName");
            String[] list = label.split(",");
            LabelPo record = new LabelPo();

            for (int i = 0; i < list.length; i++) {
                if (null == list[i] || list[i].isEmpty()) {
                    break;
                }
                Map<String, String> par = new HashMap<>();
                par.put("orgId", orgId);
                par.put("labelName", list[i]);
                par.put("labelType", "3");
                //根据标签名返回标签id
                String id = labelService.getLabelIdByName(par);
                if (null == id || id.isEmpty()) {
                    String uuid = UUID.randomUUID().toString();
                    record.setLabelId(uuid);
                    record.setLabelName(list[i]);
                    record.setOrgId(orgId);
//                    labelService.addLabel(record);
                    labelNewService.addLabel(record);
                    id = uuid;
                }
                labelId.append(",");
                labelId.append(id);
            }

            String url = systemProperties.getSync().getContentUrl() + ContentConstant.GET_ARTICLE_LIST_BY_IDS;
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("ids", x.get("articleId"));
            JSONObject jsonObject = (JSONObject) JSONArray.toJSON(param);
            String postres = httpService.doPost(url, jsonObject.toJSONString(), ContentConstant.JSON_HEADER);
            List<Map<String, Object>> resList = new ArrayList<>();
            if (null != postres) {
                Map res = (Map) JSON.parse(postres);
                if ("200".equals(res.get("code").toString())) {
                    resList = (ArrayList) res.get("data");
                    if (resList.isEmpty()) {
                        throw GlobalException.build("文章为空，请重新选择");
                    }
                    for (Map<String, Object> va : resList) {
                        String artImg = defimg;
                        if (null != va.get("newsCover")) {
                            List coverList = (List) va.get("newsCover");
                            if (coverList.size() > 0) {
                                artImg = coverList.get(0).toString();
                            }
                        }
                        Map<String, Object> data = new HashMap<>();
                        data.put("taskId", UUID.randomUUID().toString());
                        data.put("articleId", x.get("articleId"));
                        data.put("articleTitle", va.get("newsName") == null ? "标题" : va.get("newsName").toString());
                        data.put("articleDesc", va.get("newsSummary") == null ? "简介" : va.get("newsSummary").toString());
                        data.put("articleUrl", va.get("url") == null ? "" : va.get("url").toString());
                        data.put("articleImage", artImg);
                        //文章类型
                        data.put("articleType", va.get("isGoods") == null ? "0" : va.get("isGoods").toString());
                        data.put("labelId", labelId.toString().isEmpty() ? "" : labelId.toString().substring(1));
                        data.put("orgId", orgId);
                        data.put("taskType", "client");
                        data.put("readTime", va.get("readTime") == null ? 0 : va.get("readTime"));
                        data.put("url", va.get("url") == null ? "" : va.get("url"));
                        Integer addRes = iClientRobotService.addRobotArticle(data);
                        if (addRes < 1) {
                            LOGGER.warn("提交了重复的文章ID");
                            throw GlobalException.build("提交了重复的文章ID:" + x.get("articleId"));
                        }
                    }
                } else {
                    LOGGER.error("请求内容库接口失败" + res);
                    throw GlobalException.build("请求失败");
                }
            } else {
                throw GlobalException.build("请求失败");
            }
        }
    }

    /**
     * 删除营销文章
     *
     * @param session
     * @param map
     * @throws Exception
     */
    @PostMapping("/delrobotarticle")
    public void delRobotArticle(HttpServletRequest request, @RequestBody Map<String, String> map) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("taskId", map.get("taskId"));
        param.put("orgId", orgId);
        iClientRobotService.delRobotArticle(param);
    }

    /**
     * @Description: 获取机器人动态
     * @Param: [session]
     * @Return: java.util.List<cc.linker.steplink.crm.domain.RobotDynamicPo> 动态列表
     * @Author: 锋
     * @Date: 2019/9/3 16:17
     * @Version: 1.8.3
     */
    @GetMapping("/getRobotDynamicList")
    public Object getRobotDynamicList(HttpServletRequest request,
                                      @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                      @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        PageHelper.startPage(pageIndex, pageSize);
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("robotType", "client");
        return new PageInfo<>(iClientRobotService.getRobotDynamicList(param));
    }

    /**
     * 获取智能客服专员粉丝数据
     *
     * @return
     * @throws Exception
     */
    @GetMapping("getfansdata")
    public Map<String, Object> getFansData(HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> result = new HashMap<>();
        Integer totalFans = iClientRobotService.getMaintainNum(orgId);
        Integer activeFans = iClientRobotService.getActiveFans(orgId);
        String activeRate = iClientRobotService.getActivity(orgId);
        Integer maintainTimes = iClientRobotService.getMaintainTimes(orgId, "client");
        Integer maintainPerson = iClientRobotService.getMaintainPerson(orgId, "client");
        Integer adjustmentTimes = iClientRobotService.adjustmentTimes(orgId, "client");

        result.put("totalFans", totalFans);
        result.put("activeFans", activeFans);
        result.put("activeRate", activeRate);
        result.put("maintainTimes", maintainTimes);
        result.put("maintainPerson", maintainPerson);
        result.put("adjustmentTimes", adjustmentTimes);
        return result;
    }

    /**
     * 维护数据块
     *
     * @param session
     * @return
     * @throws Exception
     */
    @GetMapping("clientblock")
    public Map<String, Object> maintainBlock(HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, String> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        String tallyTime = new SimpleDateFormat("yyyy-MM-dd").format((System.currentTimeMillis()) - 86400000L);
        param.put("orgId", orgId);
        param.put("tallyTime", tallyTime);
        param.put("type", "client");
        Map<String, Object> res = iClientRobotService.maintainBlock(param);
        if (null == res || res.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("tallyTime", tallyTime);
            result.put("maintainNum", 0);
            result.put("tranRate", "0.00");
            result.put("readTime", 0);
            result.put("followNum", 0);
            result.put("unfollowNum", 0);
            result.put("activity", "0.00");
            return result;
        }
        return res;
    }

    /**
     * 维护数据折线图
     *
     * @param session
     * @param type
     * @return
     * @throws Exception
     */
    @GetMapping("clientchart")
    public List<Map<String, Object>> clientChart(HttpServletRequest request, String type) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, String> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        param.put("orgId", orgId);
        param.put("type", "client");
        param.put("kind", type);
        List<Map<String, Object>> res = iClientRobotService.robotChart(param);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (int i = 30; i > 0; i--) {
            Calendar now = Calendar.getInstance();
            now.add(Calendar.DAY_OF_MONTH, -i);
            String endDate = sdf.format(now.getTime());
            Integer up = 0;
            for (Map<String, Object> attribute : res) {
                if (attribute.get("tallyTime").toString().equals(endDate)) {
                    list.add(attribute);
                    up = 1;
                }
            }
            if (up == 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("tallyTime", endDate);
                switch (type) {
                    case "maintainNum":
                        map.put("maintainNum", 0);
                        break;
                    case "tranRate":
                        map.put("tranRate", "0.00");
                        break;
                    case "readTime":
                        map.put("readTime", 0);
                        break;
                    case "follow":
                        map.put("followNum", 0);
                        map.put("unfollowNum", 0);
                        break;
                    case "activity":
                        map.put("activity", "0.00");
                        break;
                    default:
                        break;
                }
                list.add(map);
            }
        }
        return list;

    }

    /*
     * 将时间转换为时间戳
     */
    public static Long dateToStamp(String s) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        return date.getTime();
    }
}
